package org.company.tool.tools;

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

import org.apache.velocity.VelocityContext;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.company.tool.bean.ColumnBean;
import org.company.tool.bean.EntityBean;
import org.company.tool.service.EntityTransfer;
import org.company.tool.service.imp.OracleEntityTransfer;
import org.company.tool.util.VelocityUtil;

/**
 * 文件生成函数
 * @ClassName:IbatisTools.java
 * Title:
 * Description:
 * Copyright:Copyright(c)2012
 * Company:www.si-tech.com.cn
 * @author:hucw
 * @date:2012-12-11
 * @version 1.0
 */
public class GenerateTool {
	
	private VelocityContext context = null;
	
	private EntityBean entityBean = null;
	
	/**
	 * 底层初始化方法，init方法调用
	 * @param tableName 表名 required
	 * @param packageName 包名 
	 * @param opCode 
	 * @throws SQLException
	 */
	public GenerateTool(EntityBean entityBean) throws SQLException {
	    this.entityBean = entityBean;
		EntityTransfer entityTransfer = new OracleEntityTransfer();
		List<ColumnBean> list = entityTransfer.parseColumn(entityBean.getTableName().toUpperCase());
		
		this.context = VelocityUtil.getInstance().createContext();
		context.put("entityBean", this.entityBean);
		context.put("columnBeanList", list);
	}
	
	
	
	/**
	 * 解析vmUri模板文件,生成targetUri文件
	 * @param vmUri,vm文件名称
	 * @param fileName
	 * @throws IOException 
	 * @throws Exception 
	 * @throws ParseErrorException 
	 * @throws ResourceNotFoundException 
	 */
	public void generate(String vmUri,String targetUri){
		VelocityUtil.getInstance().mergeTemplate(vmUri, targetUri, context);
		System.out.println(targetUri + " has generated");
	}
	
	/**
	 * 生成JavaBean+SqlMap文件
	 */
	public void generateJava() {
	    generatePojo();
	    generateSqlMap();
	}
	
	public void generatePojo() {
	    String packagePath = this.entityBean.getPackageName().replace(".", File.separator);
	    String targetUri = this.entityBean.getLocation() + File.separator
	            + packagePath + File.separator + this.entityBean.getJavaFileName();
        generate("vm/javabean.vm",targetUri);
	}
	
	public void generateSqlMap() {
	    String targetUri = this.entityBean.getSqlMapLocation() + File.separator + this.entityBean.getSqlMapFileName();
	    generate("vm/sqlmap.vm",targetUri);
	}
	
	/**
	 * 生成main\分页\导出页面
	 * @param opCode
	 */
	public void generatePager() {
		String opCode = (String)context.get("opCode");
		generate("vm/pager_main.vm","f" + opCode + "_main.jsp");
		generate("vm/pager_ajax_list.vm","f" + opCode + "_ajax_list.jsp");
		generate("vm/pager_ajax_exp.vm","f" + opCode + "_ajax_exp.jsp");
	}
}
